import Vue from 'vue'
import {
  SHOP_DATAS,
  ADD_COUNT,
  DEL_COUNT,
  CLEAR_CART,
  ADD_CART
} from '../mutations_type'

import {getShopInfo} from '../../network'

const state = {
  shopdatas: {},
  shopcart: [],
}

const mutations = {
  [SHOP_DATAS](state, shopdatas) {
    state.shopdatas = shopdatas
  },
  [ADD_COUNT](state, {food}) {
    if(food.count > 0) {
      food.count++
    } else {
      Vue.set(food, 'count', 1)
      state.shopcart.push(food)
    }
  },
  [DEL_COUNT](state, {food}) {
    console.log(food);
    if(food.count > 0) {
      food.count--
      if(food.count === 0) {
        state.shopcart.splice(state.shopcart.indexOf(food), 1)
      }
    }
  },
  [CLEAR_CART](state) {
    // 清空购物车之前必须把购物车中food.count清0
    state.shopcart.forEach(food => {
      food.count = 0
    })
    state.shopcart = []
  },
  [ADD_CART](state, shopcart) {
    state.shopcart = shopcart
  }
}

const actions = {
  async getShopDatasAction({commit}) {
    let result = await getShopInfo()
    !!(result.code === 0) && commit(SHOP_DATAS, result.data)
  },
  ChangeCountNum({commit}, {isAdd, food}) {
    if(isAdd) {
      commit(ADD_COUNT, {food})
    } else {
      commit(DEL_COUNT, {food})
    }
  }
}

const getters = {
  // 方法一
  // ShopCart() {
  //   return state.shopdatas.goods.reduce((pre, good) => {
  //     pre.push(good.foods.filter(food => food.count > 0))
  //     return pre
  //   }, [])
  // }
  totalCount(state) {
    return state.shopcart.reduce((pre, food) => {
      return pre += food.count
    }, 0)
  },
  totalPrice(state) {
    return state.shopcart.reduce((pre, food) => {
      return pre += food.count * food.price
    }, 0)
  },
  CommentWithGood(state) {
    return state.shopdatas.ratings.reduce((pre, rating) => {
      return pre += rating.rateType === 0 ? 1 : 0
    }, 0)
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}